import { getToken, setToken, removeToken, setTimeStamp } from "@/utils/auth"
import { login, getUserInfo, getStaffInfo } from '@/api/user'
import { resetRouter } from "@/router/index"
//状态
const state = {
    token: getToken(), //设置token为共享状态,初始化vuex的时候,就先从缓存中读取
    userInfo: {} //用户资料
}
const mutations = {
    LOGIN(state, token) {
        state.token = token //将数据设置给vuex 
            //同步给缓存
        setToken(token)
    },
    //获取用户资料
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //退出登录
    LOGOUT(state) {
        state.token = null //清空token
        removeToken() //同步给缓存
        state.userInfo = {} //清空用户信息


    }
}
const actions = {
    //登录接口
    async login(context, data) {
        const result = await login(data)
        context.commit("LOGIN", result)
        setTimeStamp() //登录时,把登录时间存进cook
            // console.log(result);
    },
    //获取用户资料
    async getUserInfo(context) {
        const userInfo = await getUserInfo()
        const staffInfo = await getStaffInfo(userInfo.userId)

        // console.log(staffInfo);
        context.commit('GETUSERINFO', {...userInfo, ...staffInfo }) //合并登录用户信息和根据用户ID的员工的信息
        return userInfo //这里为什么要return.这里是给后期做权限的时候,留下的伏笔
    },
    logout(context) {
        context.commit("LOGOUT")
        resetRouter() //重置路由 
        context.commit("permission/setRoutes", [], { root: true })
    }
}



export default {
    namespaced: true,
    state,
    mutations,
    actions
}